<template>
  <div class="users">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索栏 -->
    <div>
      <el-input
        placeholder="请输入内容"
        v-model="query"
        class="input-with-select users_search"
        @keyup.13.native="search"
        clearable
      >
        <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
      </el-input>
      <el-button type="success" plain @click="addDialogFormVisible = true">添加用户</el-button>
    </div>
    <!-- 用户信息表格 -->
    <el-table :data="userList" height="550" border style="width: 100%">
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column prop="username" label="姓名" width="150"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="mobile" label="电话"></el-table-column>
      <el-table-column label="用户状态" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.mg_state"
            @change="changeUserState(scope.row.id,scope.row.mg_state)"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="编辑" placement="top" transition="el-zoom-in-bottom">
            <el-button type="success" icon="el-icon-edit" plain @click="showEdit(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="分配角色" placement="top" transition="el-zoom-in-bottom">
            <el-button type="warning" icon="el-icon-user" plain @click="showAllot(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top" transition="el-zoom-in-bottom">
            <el-button type="danger" icon="el-icon-delete" plain @click="deleteUserById(scope.row.id)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页栏 -->
    <div class="block">
      <span class="demonstration"></span>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagenum"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogFormVisible">
      <el-form :model="addForm" :label-width="'80px'" :rules="rules" ref="addForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" clearable show-password autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile" autocomplete="off" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="allotDialogFormVisible">
      <el-form :model="allotForm" :label-width="'80px'">
        <el-form-item label="用户名" class="allotUserName">
          <el-input v-model="allotForm.username" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="allotForm.rid" placeholder="请选择角色">
            <el-option
            v-for="value in roleList"
            :key="value.id"
            :label="value.roleName"
            :value="value.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="allotDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRoleSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑用户对话框 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogFormVisible">
      <el-form :model="editForm" :label-width="'80px'" :rules="rules" ref="editForm">
        <el-form-item label="用户名" >
          <el-input v-model="editForm.username" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile" autocomplete="off" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUserList,
  addUser,
  updateUserState,
  delUserById,
  allotUserRole,
  editUser
} from '@/api/user_api'
import { getAllRoleList } from '@/api/role_api'
export default {
  data () {
    return {
      // 数据总条数
      total: 0,
      // 每页显示的数据条数
      pagesize: 5,
      // 当前页码
      pagenum: 1,
      // 用户搜索关键字
      query: '',
      userList: [],
      roleList: [],
      // 添加用户对话框的状态
      addDialogFormVisible: false,
      // 分配角色对话框的状态
      allotDialogFormVisible: false,
      // 编辑用户对话框的状态
      editDialogFormVisible: false,
      //   添加用户数据对象
      addForm: {
        username: '',
        password: '',
        email: 'a@b.com',
        mobile: '13245678978'
      },
      //   分配角色数据对象
      allotForm: {
        username: '',
        id: '',
        rid: ''
      },
      editForm: {
        id: '',
        username: '',
        email: '',
        mobile: ''
      },
      // 新增用户的表单验证规则
      rules: {
        usename: [{ required: true, message: '请填写用户名', trigger: 'blur' }],
        password: [
          { required: true, message: '请填写密码', trigger: 'blur' },
          {
            min: 6,
            max: 18,
            message: '密码长度为 6 到 18 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          // wuhu0723@126.com
          //   学习正则就是学习它的元字符
          // 1.占位符，说明这个位置需要填入满足要求的字符
          // \w:合法字符： 0-9 a-z A-Z _   \W：非法字符
          // \d:数字：0-9   \D:非数字
          // 2.修饰符：修饰前面的字符所出现的次数，前面的字符默认是指前面的一个字符，除非你使用()包含
          // +：修饰前面的字符出现1次或多次
          // ？：修饰前面的字符出现0次或1次
          // {n,m}:修饰前面的字符最少出现n次，最多出现m次
          // {n}:修饰前面的字符出现n次
          // {n,}修饰前面的字符最少出现n次，最多没有限制
          { required: true, message: '请填写Email', trigger: 'blur' },
          { pattern: /\w+[@]\w+[.]\w{2,3}/, message: '请填写正确的邮箱格式' }
        ],
        mobile: [
          { required: true, message: '请填写手机号', trigger: 'blur' },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '请填写正确的手机号(11位数字)',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  mounted () {
    this.init()
    // 加载页面时获取所有角色数据
    getAllRoleList()
      .then(res => {
        // console.log(res, 'getAllRoleList')
        if (res.data.meta.status === 200) {
          this.roleList = res.data.data
        }
      })
  },
  methods: {
    search () {
      this.pagenum = 1
      this.init()
    },
    // 切换size下拉列表时触发
    handleSizeChange (val) {
      //   重置 pagesize
      this.pagesize = val
      // 再镒拉取数据
      this.init()
    },
    // 切换当前页码
    handleCurrentChange (val) {
      //   将pagenum重置，再次发起数据请求
      this.pagenum = val
      this.init()
    },
    // 数据初始化
    init () {
      getUserList({
        query: this.query,
        pagenum: this.pagenum,
        pagesize: this.pagesize
      })
        .then(res => {
          // console.log(res, 'getUserList')
          this.userList = res.data.data.users
          // console.log(this.userList, 'userList')
          this.total = res.data.data.total
        })
        .catch(err => {
          console.error(err)
          this.$message.error(err.data.meta.msg)
        })
    },
    addUser () {
      // 1,再次实现数据的验证
      this.$refs.addForm.validate(vaild => {
        if (vaild) {
          addUser(this.addForm)
            .then(res => {
              // console.log(res, 'addUser.res')
              if (res.data.meta.status === 201) {
                //  让对话框隐藏
                this.addDialogFormVisible = false
                // 重置表单元素的数据
                this.$refs.addForm.resetFields()
                // 实现数据 刷新
                this.init()
              } else {
                this.$message({
                  type: 'error',
                  message: res.data.meta.msg
                })
              }
            })
            .catch(err => {
              console.error(err)
              this.$message.error(err.data.meta.msg)
            })
        }
      })
    },
    changeUserState (id, type) {
      updateUserState(id, type).then(res => {
        console.log(res, 'changeUserState')
        if (res.data.meta.status === 200) {
          this.$message.success(res.data.meta.msg)
        }
      })
    },
    // 删除单个用户
    deleteUserById (id) {
      // 给出删除警告
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 如果单击确定，就会执行.then
          // 真正执行删除操作
          delUserById(id)
            .then(res => {
              console.log(res, 'delUserById')
              if (res.data.meta.status === 200) {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
                // 判断本次删除之后，当前页还有没有数据，如果有数据，就保持页码为当前页，否则就到上一页
                this.pagenum =
                  Math.ceil((this.total - 1) / this.pagesize) < this.pagenum
                    ? --this.pagenum
                    : this.pagenum
                this.init()
                // console.log(this.pagenum)
              }
            })
            .catch(err1 => {
              this.$message.error('删除失败')
            })
        })
        .catch(() => {
          // 如果单击取消就会执行.catch
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 展示分配角色对话框
    showAllot (option) {
      this.allotDialogFormVisible = true
      this.allotForm.username = option.username
      this.allotForm.id = option.id
      this.allotForm.rid = option.rid
    },
    // 分配角色提交
    allotRoleSubmit () {
      // 先判断是否选择了角色
      if (!this.allotForm.rid) {
        this.$message.error('请先选择角色')
        return false
      }
      allotUserRole(this.allotForm.id, this.allotForm.rid)
        .then(res => {
          // console.log(res, 'allotUserRole')
          if (res.data.meta.status === 200) {
            this.$message.success(res.data.meta.msg)
            this.allotDialogFormVisible = false
            // 分配之后,刷新页面数据
            this.init()
            // this.allotForm.id = res.data.data.id
            // this.allotForm.rid = res.data.data.role_id
          }
        })
        .catch(err => {
          console.error(err)
          this.$message.error(err.data.meta.msg)
          this.init()
        })
    },
    // 展示编辑用户对话框
    showEdit (row) {
      this.editDialogFormVisible = true
      this.editForm.id = row.id
      this.editForm.username = row.username
      this.editForm.email = row.email
      this.editForm.mobile = row.mobile
    },
    // 编辑用户提交
    editUserSubmit () {
      // 先验证格式是否合法
      this.$refs.editForm.validate(valid => {
        if (valid) {
          editUser(this.editForm)
            .then(res => {
              console.log(res, 'editUser')
              if (res.data.meta.status === 200) {
                this.$message.success(res.data.meta.msg)
                this.editDialogFormVisible = false
                this.init()
              }
            })
        } else {
          this.$message.error('用户输入不合法')
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.users_search {
  margin: 15px 0;
  margin-right: 15px;
  width: 500px;
}
.allotUserName {
  width: 300px;
}
</style>
